package com.spring.iosservice.web.controller;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import com.aliyun.api.AliyunClient;
import com.aliyun.api.DefaultAliyunClient;
import com.aliyun.api.domain.Job;
import com.aliyun.api.domain.OSSFile;
import com.aliyun.api.mts.mts20140618.request.QueryJobListRequest;
import com.aliyun.api.mts.mts20140618.response.QueryJobListResponse;
import com.spera.aliyunContent.AliyunContent;
import com.spera.aliyunUtil.CreateOSSClient;
import com.spera.aliyunUtil.OSSFileDO;
import com.spera.aliyunUtil.SperaMTSUtil;
import com.spring.common.web.service.CommonService;
import com.spring.iosservice.web.dao.IosQuestMapper;
import com.spring.iosservice.web.model.CourseMtsInfo;
import com.spring.iosservice.web.model.MtsLog;

//检测MTS转码任务
public class VideoTransCheckOld {
	
	@Resource
	private IosQuestMapper IosQuestMapper;
	@Resource
	private MongoTemplate mongoService;
	@Resource
	private CommonService commonService;
	
	
	private AliyunClient aliyunClient = new DefaultAliyunClient(AliyunContent.MTS_SERVER_URL, AliyunContent.accessKeyId, AliyunContent.accessKeySecret);
	
	public void check(){
		List<CourseMtsInfo> list = mongoService.findAll(CourseMtsInfo.class);
		for(CourseMtsInfo one:list){
			System.out.println("检测---->"+one.getCourseVideosId());
			try{
				//文件名
				String encodedObjectName = URLEncoder.encode(one.getOssFilePath(), "utf-8");
				//转码作业还没开始
				if("0".equalsIgnoreCase(one.getTranscodeJobId())){
					Query q = new Query(Criteria.where("courseVideosId").is(one.getCourseVideosId()));
					OSSFileDO inputFile = new OSSFileDO(AliyunContent.location,AliyunContent.inputBucket,encodedObjectName);
					//模版分析作业
					/*String templateId = */SperaMTSUtil.getInstance().systemTemplateJobFlow(inputFile);
					//开始转码
					String transcodeJobId = SperaMTSUtil.getInstance().submitTranscodeJob(inputFile, AliyunContent.transcodeTemplateId);//templateId
					mongoService.updateFirst(q, Update.update("transcodeJobId", transcodeJobId), CourseMtsInfo.class);
				}else{//检测转码作业是否已进行完毕
					Job transcodeJob = checkTranscodeJobComplete(one.getTranscodeJobId());
					if(transcodeJob!=null){
						OSSFile outputFile  = transcodeJob.getOutput().getOutputFile();
//						String outputFileOSSUrl = outputFile.getLocation();
				        String outputFileOSSUrl = "http://" + outputFile.getBucket() + ".oss-cn-hangzhou.aliyuncs.com/" + outputFile.getObject();
						int i = 0;
						if("common".equalsIgnoreCase(one.getModelName())){//oss基础接口
							Map<String,Object> im = new HashMap<String,Object>();
							im.put("id", one.getCourseVideosId());
							im.put("bucket", outputFile.getBucket());
							im.put("url", outputFileOSSUrl);
							im.put("etag", one.getEtag());//video mts  无etag
							im.put("key", outputFile.getObject());
							im.put("token", one.getToken());
							im.put("file_type", "video");
							commonService.addOssFile(im);
						}
						if("coursevideo".equalsIgnoreCase(one.getModelName())){//课程视频
							Map<String, Object> s = new HashMap<String, Object>();
							s.put("id", one.getCourseVideosId());
							s.put("status", "1");
							s.put("video_src", outputFileOSSUrl);
							i = IosQuestMapper.updateVideoPhoto(s);
						}
						if(i==1){
							Query q = new Query(Criteria.where("transcodeJobId").is(one.getTranscodeJobId()));
							mongoService.remove(q, CourseMtsInfo.class);
							//删除未压缩过的视频文件
							CreateOSSClient.getInstance().getOSSClient().deleteObject(AliyunContent.inputBucket, encodedObjectName);
						}
					}
				}
			}catch(Exception e){
				e.printStackTrace();
				MtsLog msg = new MtsLog();
				msg.setCourseVideosId(one.getCourseVideosId());
				msg.setTranscodeJobId(one.getTranscodeJobId());
				msg.setOssFilePath(one.getOssFilePath());
				msg.setVideoUrl(one.getVideoUrl());
				msg.setModelName(one.getModelName());
				msg.setToken(one.getToken());
				msg.setEtag(one.getEtag());
				msg.setErrorMsg(e.getMessage().substring(0, e.getMessage().length()>100?100:e.getMessage().length()));
				mongoService.insert(msg);
				Query q = new Query(Criteria.where("transcodeJobId").is(one.getTranscodeJobId()));
				mongoService.remove(q, CourseMtsInfo.class);
			}
		}
	}
	
	//转码检测
	private Job checkTranscodeJobComplete(String transcodeJobId) {
		QueryJobListRequest request = new QueryJobListRequest();
        request.setJobIds(transcodeJobId);
        try {
            while (true) {
                QueryJobListResponse response = aliyunClient.execute(request);
                if(!response.isSuccess()) {
                    throw new RuntimeException("QueryJobListRequest failed");
            	}

                Job transcodeJob = response.getJobList().get(0);
                String status = transcodeJob.getState();

                if ("TranscodeFail".equals(status)) {
                    throw new RuntimeException("transcodeJob state Failed");
                }

                if ("TranscodeSuccess".equals(status)) {
                    return transcodeJob;
                }

                Thread.sleep(5 * 1000);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
	}
	
}
